import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import '../core/gitcode_api.dart';
import '../widgets/user_card.dart';
import 'user_detail_page.dart';

/// 带下拉刷新和上拉加载的用户列表页面
/// 支持分页加载，提供完整的刷新和加载更多功能
class UserListPage extends StatefulWidget {
  const UserListPage({
    super.key,
    required this.keyword,
    required this.token,
  });

  final String keyword;
  final String token;

  @override
  State<UserListPage> createState() => _UserListPageState();
}

class _UserListPageState extends State<UserListPage> {
  final RefreshController _refreshController = RefreshController(
    initialRefresh: false,
  );
  final GitCodeApiClient _client = GitCodeApiClient();

  List<GitCodeSearchUser> _users = [];
  int _currentPage = 1;
  final int _perPage = 20;
  bool _hasMore = true;
  String? _errorMessage;
  bool _isLoading = false;

  @override
  void initState() {
    super.initState();
    _loadUsers(refresh: true);
  }

  @override
  void dispose() {
    _refreshController.dispose();
    super.dispose();
  }

  /// 加载用户列表
  Future<void> _loadUsers({bool refresh = false}) async {
    if (_isLoading) return;

    if (refresh) {
      _currentPage = 1;
      _hasMore = true;
      _users.clear();
    }

    if (!_hasMore) {
      _refreshController.loadNoData();
      return;
    }

    setState(() {
      _isLoading = true;
      _errorMessage = null;
    });

    try {
      final users = await _client.searchUsers(
        keyword: widget.keyword,
        personalToken: widget.token,
        perPage: _perPage,
        page: _currentPage,
      );

      setState(() {
        if (refresh) {
          _users = users;
        } else {
          _users.addAll(users);
        }

        // 判断是否还有更多数据
        _hasMore = users.length >= _perPage;
        _currentPage++;
        _errorMessage = null;
        _isLoading = false;
      });

      if (refresh) {
        _refreshController.refreshCompleted();
      } else {
        if (_hasMore) {
          _refreshController.loadComplete();
        } else {
          _refreshController.loadNoData();
        }
      }
    } on GitCodeApiException catch (e) {
      setState(() {
        _errorMessage = e.message;
        _isLoading = false;
      });
      if (refresh) {
        _refreshController.refreshFailed();
      } else {
        _refreshController.loadFailed();
      }
    } catch (e) {
      setState(() {
        _errorMessage = '加载失败：$e';
        _isLoading = false;
      });
      if (refresh) {
        _refreshController.refreshFailed();
      } else {
        _refreshController.loadFailed();
      }
    }
  }

  /// 下拉刷新
  void _onRefresh() {
    _loadUsers(refresh: true);
  }

  /// 上拉加载
  void _onLoading() {
    _loadUsers(refresh: false);
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final scheme = theme.colorScheme;
    final muted = scheme.onSurfaceVariant;

    return Scaffold(
      appBar: AppBar(
        title: Text('用户列表: ${widget.keyword}'),
      ),
      body: _errorMessage != null && _users.isEmpty
          ? Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(
                    Icons.error_outline,
                    size: 64,
                    color: scheme.error,
                  ),
                  const SizedBox(height: 16),
                  Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 32),
                    child: Text(
                      _errorMessage!,
                      style: TextStyle(color: scheme.onErrorContainer),
                      textAlign: TextAlign.center,
                    ),
                  ),
                  const SizedBox(height: 16),
                  ElevatedButton(
                    onPressed: () => _onRefresh(),
                    child: const Text('重试'),
                  ),
                ],
              ),
            )
          : SmartRefresher(
              controller: _refreshController,
              enablePullDown: true,
              enablePullUp: _hasMore,
              header: const ClassicHeader(
                refreshingText: '刷新中...',
                completeText: '刷新完成',
                idleText: '下拉刷新',
                releaseText: '释放刷新',
              ),
              footer: ClassicFooter(
                loadingText: '加载中...',
                noDataText: '没有更多数据了',
                idleText: '上拉加载更多',
                canLoadingText: '释放加载',
              ),
              onRefresh: _onRefresh,
              onLoading: _onLoading,
              child: _users.isEmpty && _isLoading
                  ? const Center(
                      child: CircularProgressIndicator(),
                    )
                  : _users.isEmpty
                      ? Center(
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Icon(
                                Icons.search_off,
                                size: 64,
                                color: muted.withValues(alpha: 0.4),
                              ),
                              const SizedBox(height: 16),
                              Text(
                                '暂无数据',
                                style: TextStyle(
                                  color: muted,
                                  fontSize: 16,
                                ),
                              ),
                            ],
                          ),
                        )
                      : ListView.builder(
                          itemCount: _users.length,
                          padding: const EdgeInsets.symmetric(vertical: 8),
                          itemBuilder: (context, index) {
                            return UserCard(
                              user: _users[index],
                              onTap: () {
                                Navigator.of(context).push(
                                  MaterialPageRoute(
                                    builder: (context) => UserDetailPage(
                                      username: _users[index].login,
                                      token: widget.token,
                                    ),
                                  ),
                                );
                              },
                            );
                          },
                        ),
            ),
    );
  }
}

